import store from '@/utils/store';
import { LogoutOutlined, UserOutlined } from '@ant-design/icons';
import { history, useModel } from '@umijs/max';
import { Avatar, Menu } from 'antd';
import type { MenuInfo } from 'rc-menu/lib/interface';
import React from 'react';
import HeaderDropdown from '../HeaderDropdown';

export type GlobalHeaderRightProps = {
  menu?: boolean;
  children?: React.ReactNode;
};

/**
 * 显示用户名组件
 */
export const AvatarName = () => {
  const { initialState } = useModel('@@initialState');
  // 不需要使用 currentUser，直接返回固定值
  return (
    <span className="anticon" style={{ color: 'white' }}>
      {initialState?.currentUser?.name}123456
    </span>
  );
};

/**
 * 头像下拉菜单组件
 */
export const AvatarDropdown: React.FC<GlobalHeaderRightProps> = () => {
  const { setInitialState } = useModel('@@initialState');

  /**
   * 退出登录，并且将当前的 url 保存
   */
  const loginOut = async () => {
    store.removeLocal('info');
    store.removeLocal('token');
    setInitialState((s) => ({ ...s, currentUser: undefined }));
    setTimeout(() => {
      history.replace('/user/login');
    }, 500);
  };

  /**
   * 进入个人中心
   */
  const goToCenter = () => {
    history.push('/userCenter');
  };

  const menuItems = [
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: '退出登录',
      onClick: loginOut,
    },
    {
      key: 'center',
      icon: <UserOutlined />,
      label: '个人中心',
      onClick: goToCenter,
    },
  ];

  const handleMenuClick = (event: MenuInfo) => {
    const { key } = event;
    const item = menuItems.find((item) => item.key === key);
    if (item && item.onClick) {
      item.onClick();
    }
  };

  const menuHeaderDropdown = <Menu selectedKeys={[]} onClick={handleMenuClick} items={menuItems} />;

  return (
    <HeaderDropdown overlay={menuHeaderDropdown}>
      <Avatar size="small" icon={<UserOutlined />} alt="avatar" />
    </HeaderDropdown>
  );
};
